// src/store/GlobalState.tsx
import React, { createContext, useContext, useReducer, ReactNode } from "react";

type State = {
  services: Array<{ id: number; domain: string; port: number; status: "running" | "stopped" }>;
};

type Action =
  | { type: "SET_SERVICES"; payload: State["services"] }
  | { type: "UPDATE_SERVICE"; payload: { id: number; status: "running" | "stopped" } };

const initialState: State = {
  services: [],
};

const GlobalStateContext = createContext<{ state: State; dispatch: React.Dispatch<Action> } | undefined>(undefined);

function reducer(state: State, action: Action): State {
  switch (action.type) {
    case "SET_SERVICES":
      return { ...state, services: action.payload };
    case "UPDATE_SERVICE":
      return {
        ...state,
        services: state.services.map((s) =>
          s.id === action.payload.id ? { ...s, status: action.payload.status } : s
        ),
      };
    default:
      return state;
  }
}

export const GlobalStateProvider = ({ children }: { children: ReactNode }) => {
  const [state, dispatch] = useReducer(reducer, initialState);
  return <GlobalStateContext.Provider value={{ state, dispatch }}>{children}</GlobalStateContext.Provider>;
};

export const useGlobalState = () => {
  const context = useContext(GlobalStateContext);
  if (!context) throw new Error("useGlobalState must be used within a GlobalStateProvider");
  return context;
};
